<?php
/**
 * Helper class to read .properties fiels
 */
class Translator_Properties {
	/**
	 * @param string $txtProperties
	 * @author Rafael Sanchez
	 * @link http://blog.rafaelsanches.com/2009/08/05/reading-java-style-properties-file-in-php/
	 */
	public function parse($txtProperties) {
		$result = array();
		$lines = explode("\n", file_get_contents($txtProperties));
		$key = "";
		$isWaitingOtherLine = false;
		foreach ($lines as $i => $line) {
			if (empty($line) || (!$isWaitingOtherLine && strpos($line, "#") === 0))
				continue;

			if (!$isWaitingOtherLine) {
				$key = substr($line, 0, strpos($line, '='));
				$value = substr($line, strpos($line, '=')+1, strlen($line));
			}
			else {
				$value .= $line;
			}

			/* Check if ends with single '\' */
			if (strrpos($value, "\\") === strlen($value)-strlen("\\")) {
				$value = substr($value,0,strlen($value)-1)."\n";
				$isWaitingOtherLine = true;
			}
			else {
				$isWaitingOtherLine = false;
			}

			$result[$key] = $value;
			unset($lines[$i]);
		}

		return $result;
	}
	
	/**
	 * Compare the two given arrays and return another one based upon
	 * certain criterias:
	 *  - A key in the new array is set if and only if it's available in
	 *    $original.
	 *  - If a value is both in $original and $translation the value
	 *    from $translation is used.
	 *  - If a value is in $original but not $translation the value of the 
	 *    entry in the new array is set to null.
	 * 
	 * @param array $keyIds
	 * @param array $translation
	 * 
	 * @return array 
	 */
	public function combine($keyIds, $translation) {
		$combined = array();
		
		foreach($keyIds as $key => $id) {
			if(isset($translation[$key])) {
				$combined[$key] = array('id' => $id, 'value' => $translation[$key]);
			} else {
				$combined[$key] = array('id' => $id, 'value' => null);
			}
		}
		
		return $combined;
	}
}